<template>
  <el-container style="display: flex; flex-direction: column; height: 100%;">
    <el-main style="flex-grow: 1; display: flex; flex-direction: column; overflow-y: hidden;">
      <div class="chat-wrapper" style="flex-grow: 1; overflow-y: auto;">
        <div class="chat-container">
          <div class="messages" ref="messages">
            <!-- 渲染消息 -->
            <div v-for="(message, index) in messages" :key="index" :class="['message', message.isUser ? 'user' : 'bot']">
              <img :src="message.isUser ? userAvatar : botAvatar" class="avatar" />
              <div class="message-bubble">
                {{ message.content || message.bot_response }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-main>

    <!-- 猜你想问的部分（位置调整在输入框上面） -->
    <div class="quick-questions">
      <div class="quick-questions-header">猜你想问:</div>
      <div v-for="(question, index) in quickQuestions" :key="index" class="quick-question-bubble" @click="insertQuickQuestion(question)">
        {{ question }}
      </div>
    </div>

    <!-- 输入框和发送按钮 -->
    <div class="chat-input">
      <div class="input-container">
        <input 
          v-model="newMessage" 
          @keyup.enter="sendMessage" 
          placeholder="输入消息..." 
          :disabled="isSending" 
        />
        <el-button 
          type="success" 
          @click="sendMessage" 
          :disabled="!newMessage.trim() || isSending"
        >
          发送
        </el-button>
      </div>
    </div>
  </el-container>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      messages: [],
      newMessage: '',
      userAvatar: 'https://th.bing.com/th/id/R.83933e899522a1c1428bd600ce88ed44?rik=e3F8UnyAmcK46g&pid=ImgRaw&r=0&sres=1&sresct=1',
      botAvatar: 'https://th.bing.com/th/id/OIP.AT2HzcMU5twFwuTUORc8PwAAAA?rs=1&pid=ImgDetMain',
      quickQuestions: [
        '你好！',
        '你是谁？',
        '武汉天气如何？',
        '你能做些什么？',
      ],
      isSending: false,
      userId: null, // 保存用户的ID
    };
  },
  created() {
    // 从 sessionStorage 获取 token
    const token = sessionStorage.getItem('jwt_token');

    if (token) {
      this.fetchChatHistory(token);
    }
  },
  methods: {
    // 获取聊天历史消息
    async fetchChatHistory(token) {
      try {
        const response = await axios.get('http://localhost:5000/user/messages/', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
        const formattedMessages = response.data.map(msg => [
          { content: msg.content, isUser: true },
          { bot_response: msg.bot_response, isUser: false }
        ]).flat();
        this.messages = formattedMessages;
      } catch (error) {
        console.error('获取聊天记录失败:', error.response || error);  // 输出完整的错误信息
      }
      this.scrollToBottom();
    },

    // 发送消息
    async sendMessage() {
      if (this.newMessage.trim() && !this.isSending) {
        this.isSending = true;
        const userMessage = { content: this.newMessage }; // 将 userId 包含在发送的消息中
        this.messages.push({ content: this.newMessage, isUser: true });
        this.newMessage = '';
        this.scrollToBottom();
        
        try {
          // 从 sessionStorage 获取 token
          const token = sessionStorage.getItem('jwt_token');
          const response = await axios.post('http://localhost:5000/user/chat', userMessage, {
            headers: {
              Authorization: `Bearer ${token}`  // 将 token 作为 Authorization 头部传递
            }
          });

          const botMessage = response.data;
          this.messages.push({ bot_response: botMessage.bot_response, isUser: false });
        } catch (error) {
          console.error('发送消息失败:', error);
        }

        this.isSending = false;
        this.scrollToBottom();
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const messagesContainer = document.querySelector('.chat-wrapper');
        if (messagesContainer) {
          messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
      });
    },

    insertQuickQuestion(question) {
      this.newMessage = question;
      this.scrollToBottom();
    }
  }
};
</script>

<style scoped>
.chat-wrapper {
  display: flex;
  flex-direction: column;
  padding: 10px;
  height: 100%;
}

.messages {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  overflow-y: auto;
  padding-right: 10px;
}

.message {
  display: flex;
  align-items: flex-start;
  margin: 5px 0;
}

.message.user {
  justify-content: flex-end; /* 用户消息右对齐 */
}

.message.bot {
  justify-content: flex-start; /* 机器人消息左对齐 */
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.message-bubble {
  background-color: #f1f0f0;
  padding: 12px;
  border-radius: 20px;
  max-width: 70%;
  word-wrap: break-word;
  font-size: 16px;
  line-height: 1.4;
}

/* 更改用户消息气泡颜色 */
.message.user .message-bubble {
  background-color: #add8e6; /* 淡蓝色 */
}

.chat-input {
  position: sticky;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 12px;
  border-top: 1px solid #ddd;
  z-index: 1;
}

.input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

input {
  padding: 12px;
  width: calc(100% - 90px); /* 输入框占据剩余空间，减去按钮的宽度 */
  border: 1px solid #ccc;
  border-radius: 25px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  border-color: #3498db;
}

.el-button {
  margin-left: 12px;
  margin-right: 20px;
  width: 80px;
  height: 40px;
  border-radius: 30px;
}

/* 快速问题气泡样式 */
.quick-questions {
  margin-bottom: 10px;
  padding: 10px 0;
  margin-left: 20px;
  border-radius: 12px;
  padding-left: 15px;
  padding-right: 15px;
  transition: all 0.3s ease;
  animation: gradientAnimation 10s infinite; /* 背景渐变动画 */
}

.quick-questions-header {
  font-size: 18px;
  font-weight: bold;
  color: #4e5b7c;
  margin-left: 10px;
  margin-bottom: 10px;
}

.quick-question-bubble {
  display: inline-flex;
  background-color: rgba(241, 240, 240, 0.8);
  padding: 12px 20px;
  border-radius: 30px;
  align-items: center;
  justify-content: center;
  margin: 0 12px 8px 0;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 微弱阴影 */
}

.quick-question-bubble:hover {
  background-color: rgba(225, 225, 225, 0.8);
  transform: scale(1.05); /* 放大效果 */
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15); /* 添加更多阴影 */
}

@keyframes gradientAnimation {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>
